<?php
namespace app\admin\controller;

use think\Db;
use think\Controller;
use Godok\Org\Auth;
use think\Config;

class Index extends Base
{
    /**
     * 控制台
     */
    // http://127.0.0.1/auth/Index/index
    public function index()
    {
        $groupids = \Godok\Org\Auth::user('groupids');
        $data = ['groupname'=>'游客'];
        if( !empty($groupids) ) {
            $group = Db::name( Config::get('auth.table_group') )->where(['id' => $groupids[0]])->find();
            if ( $group ) {
                $data['groupname'] = $group['title'];
            }
        }
        $data['menu'] = $this->menu2Html( \Godok\Org\Auth::menu("ismenu=1 AND status=1") );

		return $this->fetch('index',$data);
    }

    
    /**
     * 首页
     */
    public function home(){
        // $this->redirect(url('Statistics/index'));
        $iw=Request()->param();

        $start_time=isset($iw['start_time'])?strtotime($iw['start_time']):'';
        $end_time=isset($iw['end_time'])?strtotime($iw['end_time']):'';

        if($end_time){
            $_end_time=getOneDay($end_time);
            // $_end_time=$_end_time['et'];
            if ($end_time==$_end_time['st']) {
                $end_time=$_end_time['et'];
            }
        }else{
            $end_time=getOneDay();
            $end_time=$end_time['et'];
        }

        if ($start_time) {
            // $start_time=getOneDay($start_time);
            // $start_time=$start_time['st'];
        }else{
            $start_time=getDayRegion($end_time,7);
            $start_time=$start_time['st'];
        }
        
        $iw['start_time']=date('Y-m-d H:i:s',$start_time);
        $iw['end_time']=date('Y-m-d H:i:s',$end_time);
        if ($iw['selt']!=='0') {
            $iw['selt']=$iw['selt']?:8;
        }
        $data['w']=$iw;

        $opt = ['start_time'=>$start_time,'end_time'=>$end_time];
        $data['Tcount']['Uc'] = self::users($opt);

        $order = self::order($opt);
        $data['Tcount']['order']['num']   = sizeof($order);
        $data['Tcount']['order']['total'] = array_sum(array_column($order, 'order_money'));

        $stock = self::stock($opt);
        $stockint = []; $stockout = [];
        foreach ($stock as $k => $v) {
            if ($v['type'] > 0) {
                $stockint[] = $v;
            }else{
                $stockout[] = $v;
            }
        }

        $data['Tcount']['stockint'] = self::countStock($stockint);
        $data['Tcount']['stockout'] = self::countStock($stockout);

        $dayMap=getDayMapSE($start_time,$end_time);
        foreach ($dayMap as $k => $v) {
            $data['dayMap'] .= '"'.date('Y-m-d',$k).'",';
        }
        $data['dayMap'] = '['.rtrim($data['dayMap'],',').']'; // 按天显示
        
        $data['orderDay'] = self::orderDay($order,$dayMap); // 订单按天显示

        $data['stockintDay'] = self::stockDay($stockint,$dayMap); // 入库按天显示

        $data['stockoutDay'] = self::stockDay($stockout,$dayMap); // 出库按天显示
        return $this->fetch('',$data);
    }

    /**
     * 格式化菜单
     */
    private  function menu2Html($list,$level = 0)
    {
        $menu = '';
        $menulevel = ['first','second','third'];
        if ( is_array($list) ) {
            if( $level > 2 ) {
                $level = 2;
            }
            $menu .= $level > 0  ? '<ul class="nav nav-'.$menulevel[$level].'-level">' : '';
            foreach ( $list as $li ) {
                $menu .= '<li>';
                if( empty($li['module']) || empty($li['controller']) || '*' == $li['module'] || '*' == $li['controller'] ) {
                    $menu .= '<a href="javascript:void(0)" >';
                } else {
                    $act = explode(',',$li['action']);
                    $href = \think\Request::instance()->root().'/'. $li['module'] . '/' . $li['controller'] . '/' . $act[0];
                    if( !empty($li['condition']) ) {
                        $href .= '?' . $li['condition'];
                    }
                    $menu .= '<a href="' . $href . '" class="J_menuItem">';
                }
    
                if ( !empty($li['icon']) ) {
                    $menu .= '<i class="' . $li['icon'] . '"></i> ';
                }
                $menu .= '<span class="nav-label">' . $li['title'] . '</span>';
                if ( isset($li['children']) ) {
                    $children = $this->menu2Html($li['children'], $level + 1 );
                    $menu .= ' <span class="fa arrow"></span>';
                } else {
                    $children = '';
                }
                $menu .= '</a>' . $children;
                $menu .= '</li>';
            }
    
            $menu .= $level > 0 ? '</ul>' : '';
            return $menu;
        } else {
            return '';
        }
    }

    /**
     * 统计出入库
     * @param  [type] $stock [description]
     * @return [type]        [description]
     */
    function countStock($stock){
        $num=0; $total=0;
        foreach ($stock as $k => $v) {
            $num=$num+$v['num'];
            $total=$total+($v['price']*$v['num']);
        }
        return ['num'=>$num,'total'=>$total];
    }

    /**
     * 新增用户数
     * @return [type] [description]
     */
    function users($opt=[]){
        $count = Db::name('user')->where('register_time','between',[$opt['start_time'],$opt['end_time']])->count();
        return $count;
    }

    /**
     * 订单数量金额
     * @return [type] [description]
     */
    function order($opt=[]){
        $orders = Db::name('order')->where('create_time','between time',[$opt['start_time'],$opt['end_time']])->where('order_status>=20')->select();
        return $orders;
    }

    /**
     * 出入库数量
     * -10：退货出库
        -1  ：配送出库
         1  ：采购入库
         10：退单入库
     * @param opt['type'] = 1 入库数据 else 出库
     * @return [type] [description]
     */
    function stock($opt=[]){
        $stock = Db::name('stock_detail')->where('time','between time',[$opt['start_time'],$opt['end_time']])->select();
        return $stock;
    }

    /**
     * 按天统计订单
     * @param  [type] $order  [description]
     * @param  [type] $dayMap [description]
     * @return [type]         [description]
     */
    function orderDay($order,$dayMap)
    {
        $order_arr=array();
        foreach ($order as $k => $v) {
            $order_arr[date('Y-m-d',strtotime($v['create_time']))][]=$v;
        }

        foreach ($dayMap as $key => $value) {
            if (isset($order_arr[date('Y-m-d',$key)])) {
                $curOD=$order_arr[date('Y-m-d',$key)];
                $curT.=count($curOD).',';//订单数
                $curM.=array_sum(array_column($order_arr[date('Y-m-d',$key)], 'order_money')).',';
            }else{
                $curT.='0,';$curM.='0,';
            }
        }
        
        $Tmap='['.rtrim($curT,',').']';
        $Mmap='['.rtrim($curM,',').']';
        return array('Tmap'=>$Tmap,'Mmap'=>$Mmap);
    }

    /**
     * 出入库按天显示
     * @param  [type] $order  [description]
     * @param  [type] $dayMap [description]
     * @return [type]         [description]
     */
    function stockDay($order,$dayMap){
        $order_arr=array();
        foreach ($order as $k => $v) {
            $order_arr[date('Y-m-d',strtotime($v['time']))][]=$v;
        }

        foreach ($dayMap as $key => $value) {
            if (isset($order_arr[date('Y-m-d',$key)])) {
                $curOD=$order_arr[date('Y-m-d',$key)];
                $curT.=count($curOD).',';//订单数
                foreach ($curOD as $k => $v) {
                    $tmp_curM += $v['num']*$v['price'];
                }
                $curM.=$tmp_curM.',';
            }else{
                $curT.='0,';$curM.='0,';
            }
        }
        
        $Tmap='['.rtrim($curT,',').']';
        $Mmap='['.rtrim($curM,',').']';
        return array('Tmap'=>$Tmap,'Mmap'=>$Mmap);
    }

    public function notice()
    {
        $order = Db::name('order')->where(['order_status' => 20, 'pay_status' => 1])->order('create_time asc')->select();
        $return_arr = [];
        foreach ($order as $k => $v) {
            $tmp = [
                'type'    => 'order',
                'content' => $v['receiver_name'].' '.$v['receiver_mobile'].' '.$v['receiver_pcd'].$v['receiver_address'],
                'time'    => $v['pay_time']
            ];
            $return_arr[] = $tmp;
        }

        $purgoods = Db::name('purchase_goods')->where(['status'=>2])->order('cancel_time asc')->select();
        foreach ($purgoods as $k => $v) {
            $tmp = [
                'type'    => 'Pcancel',
                'content' => $v['remark'],
                'time'    => $v['cancel_time']
            ];
            $return_arr[] = $tmp;
        }

        array_multisort(array_column($return_arr,'time'), SORT_ASC, $return_arr);
        if ($return_arr) {
            $this->success('','',$return_arr);
        }else{
            $this->error();
        }
    }
}
